/*
* Conditions Of Use
*
* This software was developed by employees of the Sigmatrix(Beijing) Corporation.
* This software is provided by sigmatrix as a service and is expressly
* provided "AS IS."  Sigmatrix MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY.  Sigmatrix does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement.
*
*/
package com.sigmatrix.h5.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.sigmatrix.h5.dao.WarehouseDao;
import com.sigmatrix.h5.dao.impl.common.impl.BaseDaoImpl;
import com.sigmatrix.h5.dto.WarehouseData;
import com.sigmatrix.h5.entity.Warehouse;
import com.sigmatrix.h5.exception.DaoException;
import com.sigmatrix.h5.utils.Cons;
import com.sigmatrix.h5.utils.Utils;

/**
 * @ClassName: WarehouseDaoImpl
 * @Description: 仓库数据库操作接口实现
 * @author youjun 
 * @date 2017-06-24 17:31:11
 */
@Repository(value = "warehouseDao")
public class WarehouseDaoImpl extends BaseDaoImpl<Warehouse> implements WarehouseDao {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(WarehouseDaoImpl.class);

	/** 注入jdbcTemplate */
	@Autowired
	private transient JdbcTemplate jdbcTemplate;

	/**表名*/
	public static final String TABLE_NAME = "_dealers_warehouse";
	
	/**
	 *@Title: findById
	 *@Description: TODO()
	 *@return Warehouse
	 *@author youjun
	 *@date 2017年7月15日 下午1:43:37
	 *@param id
	 *@param enterpriseCode
	 *@return
	 *@throws DaoException
	 */
	@Override
	public Warehouse findById(final Integer id, final String enterpriseCode) throws DaoException {
		final StringBuilder sql = new StringBuilder("SELECT * FROM ");
		sql.append(getTname(enterpriseCode, TABLE_NAME))
		.append(" WHERE _id = ").append(id);
		final List<Warehouse> list = jdbcTemplate.query(sql.toString(), new WarehouseRowMapper());
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	/**
	 *@Title: findListByCondition
	 *@Description: TODO()
	 *@return List<Warehouse>
	 *@author youjun
	 *@date 2017年7月15日 下午1:43:22
	 *@param warehouse
	 *@return
	 *@throws DaoException
	 */
	@Override
	public List<Warehouse> findListByCondition(final Warehouse warehouse, final String enterpriseCode) throws DaoException {

		final StringBuilder sql = new StringBuilder("SELECT * FROM ").append(getTname(enterpriseCode, TABLE_NAME));
		final List<Object> paramList = new ArrayList<Object>();
		sql.append(" WHERE _status <> ?");
		paramList.add(Cons.STATUS_DELETE);
		sql.append(assemblyWhereConditon(warehouse, paramList, true));
		try {
			return jdbcTemplate.query(sql.toString(), paramList.toArray(), new WarehouseRowMapper());
		} catch (DataAccessException e) {
			throw new DaoException(e);
		}
	}
	
	/**(non-Javadoc)
	 *@Title: findPartColumnListByCondition
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.dao.WarehouseDao#findPartColumnListByCondition(com.sigmatrix.sc.handheld.inter.web.vo.WarehouseVo)
	 *@author youjun
	 *@date 2017年6月27日 上午11:33:32
	 */
	@Override
	public List<WarehouseData> findPartColumnListByCondition(final Warehouse warehouse, final String enterpriseCode) throws DaoException {

		final StringBuilder sql = new StringBuilder("SELECT _id, _code, _name FROM ").append(getTname(enterpriseCode, TABLE_NAME));
		final List<Object> paramList = new ArrayList<Object>();
		sql.append(" WHERE _status <> ?");
		paramList.add(Cons.STATUS_DELETE);
		sql.append(assemblyWhereConditon(warehouse, paramList, true));
		try {
			return jdbcTemplate.query(sql.toString(), paramList.toArray(), new RowMapper<WarehouseData>(){

				@Override
				public WarehouseData mapRow(final ResultSet resultSet, final int rowNum) throws SQLException {

					final WarehouseData warehouse = new WarehouseData();
					warehouse.setWarehouseId(resultSet.getInt("_id"));
					warehouse.setWarehouseCode(resultSet.getString("_code"));
					warehouse.setWarehouseName(resultSet.getString("_name"));
					return warehouse;
				}
			});
		} catch (DataAccessException e) {
			throw new DaoException(e);
		}
	}
	
	/**
	 * (non-Javadoc)
	 *@Title: findPartByDealerId
	 *@Description: 
	 *@see com.sigmatrix.h5.dao.WarehouseDao#findPartByDealerId(java.lang.String, java.lang.Integer)
	 *@author 
	 *@date 2017年9月14日 下午9:05:33
	 */
	public List<WarehouseData> findPartByDealerId(final String eseCode,final Integer dealerId) throws DaoException {
		if(Utils.isEmpty(eseCode)||Utils.isEmpty(dealerId)){
			throw new DaoException("请求参数有误");
		}
		final StringBuilder sql = new StringBuilder()
		.append("SELECT _id, _code, _name FROM ")
		.append(getTname(eseCode, TABLE_NAME))
		.append(" WHERE _status = ").append(Cons.STATUS_ENABLE)
		.append(" AND _dealer_id = ").append(dealerId);
		LOGGER.info(sql.toString());
		try {
			return jdbcTemplate.query(sql.toString(), new WarehouseDataRowMapper());
		} catch (DataAccessException e) {
			throw new DaoException(e);
		}
	}
	
	/**
	 * @ClassName: WarehouseRowMapper
	 * @Description: 封装返回的实体
	 * @author youjun 
	 * @date 2017-06-24 17:31:11
	 */
	public class WarehouseDataRowMapper implements RowMapper<WarehouseData> {
		public WarehouseData mapRow(final ResultSet resultSet, final int rowNum) throws SQLException {
			final WarehouseData warehouse = new WarehouseData();
			warehouse.setWarehouseId(resultSet.getInt("_id"));
			warehouse.setWarehouseCode(resultSet.getString("_code"));
			warehouse.setWarehouseName(resultSet.getString("_name"));
			return warehouse;
		}
	}

	/**
	 *@Title: assemblyWhereConditon
	 *@Description: 根据条件组装sql的where条件部分
	 *@return Object
	 *@author youjun
	 *@date 2017年6月27日 下午2:02:40
	 *@param warehouse
	 *@param paramList
	 *@param isExistWhereCondition
	 *@return
	 * @throws DaoException 
	 */
	private String assemblyWhereConditon(final Warehouse warehouse, final List<Object> paramList, final boolean isExistWhereCondition) throws DaoException {

		if(paramList==null) {
			throw new DaoException("传递的参数列表不能为null");
		}
		final StringBuilder whereSql = new StringBuilder();
		if(!isExistWhereCondition) {
			whereSql.append(" WHERE 1=1");
		}
		if(warehouse!=null) {
			if(Utils.isNotEmpty(warehouse.getName())) {
				whereSql.append(" AND _name like ?");
				paramList.add(new StringBuilder("%").append(warehouse.getName()).append("%"));
			}
		}
		return whereSql.toString();
	}

	/**
	 * @ClassName: WarehouseRowMapper
	 * @Description: 封装返回的实体
	 * @author youjun 
	 * @date 2017-06-24 17:31:11
	 */
	public class WarehouseRowMapper implements RowMapper<Warehouse> {
		public Warehouse mapRow(final ResultSet rs, final int rowNum) throws SQLException {
			final Warehouse obj = new Warehouse();
	        obj.setId(rs.getInt("_id"));
	        obj.setCode(rs.getString("_code"));  
	        obj.setName(rs.getString("_name"));
	        obj.setDealerId(rs.getInt("_dealer_id"));;
	        obj.setStatus(rs.getShort("_status"));
	        obj.setProvinceId(rs.getInt("_province_id"));
	        obj.setCityId(rs.getInt("_city_id"));
	        obj.setCitySubOrdinate(rs.getInt("_city_sub_ordinate"));
	        obj.setAddress(rs.getString("_address"));
	        obj.setCreatorId(rs.getInt("_creator_id"));
	        obj.setCreateTime(rs.getTimestamp("_create_time"));
	        obj.setUpdateId(rs.getInt("_update_id"));
	        obj.setUpdateTime(rs.getTimestamp("_update_time"));
	        obj.setEnableId(rs.getInt("_enable_id"));
	        obj.setEnableTime(rs.getTimestamp("_enable_time"));
	        obj.setDisableId(rs.getInt("_disable_id"));
	        obj.setDisableTime(rs.getTimestamp("_disable_time"));
	        obj.setRemarks(rs.getString("_remarks"));
	        return obj; 
		}
	}

	/**
	 * (non-Javadoc)
	 *@Title: findPartByDealerIdDefault
	 *@Description: 
	 *@see com.sigmatrix.h5.dao.WarehouseDao#findPartByDealerIdDefault(java.lang.String, java.lang.Integer)
	 *@author gaomingkai
	 *@date 2017年11月17日 下午3:54:05
	 */
	@Override
	public List<WarehouseData> findPartByDealerIdDefault(String eseCode, Integer dealerId) throws DaoException {
		if(Utils.isEmpty(eseCode)||Utils.isEmpty(dealerId)){
			throw new DaoException("请求参数有误");
		}
		final StringBuilder sql = new StringBuilder()
		.append("SELECT _id, _code, _name FROM ")
		.append(getTname(eseCode, TABLE_NAME))
		.append(" WHERE _status = ").append(Cons.STATUS_ENABLE)
		.append(" AND _dealer_id = ").append(dealerId).append(" AND _is_default = ").append(Cons._DEALERS_WAREHOUSE_DEFAULT);
		LOGGER.info(sql.toString());
		try {
			return jdbcTemplate.query(sql.toString(), new WarehouseDataRowMapper());
		} catch (DataAccessException e) {
			throw new DaoException(e);
		}
	}
	
	

}
